import numpy as np
import matplotlib.pyplot as plt

# 参数设置
sample_rate = 1000  # 采样率
duration = 20  # 信号持续时间
frequency = 0.2  # 正弦波频率
amplitude = 400  # 正弦波幅值
phaseDif = 0.4 # 相位差

# 生成时间序列
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)

# 生成递增分量的正弦波形
increment = np.linspace(0, 1500, len(t))  # 添加递增分量
signal1 = amplitude * np.sin(2 * np.pi * frequency * t) + increment
signal2 = amplitude * np.sin(2 * np.pi * frequency * t + phaseDif) + increment  # 相位差为π/2

# 计算傅里叶变换
fft_signal1 = np.fft.fft(signal1)
fft_signal2 = np.fft.fft(signal2)
freqs = np.fft.fftfreq(len(t), 1 / sample_rate)

# 绘制原波形在一幅图中，一条红色，一条黄色
plt.figure(figsize=(12, 6))
plt.plot(t, signal1, 'r', label='Signal 1 (Red)')
plt.plot(t, signal2, 'y', label='Signal 2 (Yellow)')
plt.title('Original Signals')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.legend()
plt.grid(True)
plt.show()

# 找到频率为0.1 Hz时的索引
frequency_index = np.where(freqs == frequency)

# 归一化相位到0~255范围
normalized_phase1 = np.angle(fft_signal1) * (180 / np.pi) + 180
normalized_phase2 = np.angle(fft_signal2) * (180 / np.pi) + 180

# 绘制傅里叶变换的相位图中特定频率的数据点
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.plot(freqs[frequency_index], normalized_phase1[frequency_index], 'ro', label='Signal 1 Phase (Red)')
plt.plot(freqs[frequency_index], normalized_phase2[frequency_index], 'yo', label='Signal 2 Phase (Yellow)')
plt.title(f'Phase Spectra at {frequency} Hz (Normalized to 0-255)')
plt.xlabel('Frequency (Hz)')
plt.xlim(frequency - 0.01, frequency + 0.01)
plt.ylim(0, 255)
# 标出点的数值
y1 = normalized_phase1[frequency_index]
y2 = normalized_phase2[frequency_index]
plt.annotate(f'{y1}', (frequency, y1), textcoords="offset points", xytext=(10, 0), ha='left', fontsize=10)
plt.annotate(f'{y2}', (frequency, y2), textcoords="offset points", xytext=(10, 0), ha='left', fontsize=10)
plt.legend()
plt.grid(True)


plt.subplot(1, 2, 2)
plt.plot(freqs[frequency_index], abs(normalized_phase2[frequency_index] - normalized_phase1[frequency_index]), 'bo', label='Signal diff Phase  (blue)')
plt.title(f'Phase diff at {frequency} Hz (Normalized to 0-255)')
plt.xlabel('Frequency (Hz)')
plt.xlim(frequency - 0.01, frequency + 0.01)
# plt.ylim(0, 30)
abs = abs(normalized_phase2[frequency_index] - normalized_phase1[frequency_index])
plt.annotate(f'{abs}', (frequency, abs), textcoords="offset points", xytext=(10, 0), ha='left', fontsize=10)
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()
